package com.atguigu.srb.core.controller.api;


import com.alibaba.fastjson.JSON;
import com.atguigu.common.result.R;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.pojo.vo.UserBindVO;
import com.atguigu.srb.core.pojo.vo.UserInfoVO;
import com.atguigu.srb.core.service.UserBindService;
import com.atguigu.srb.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 用户绑定表 前端控制器
 * </p>
 *
 * @author gcq
 * @since 2021-04-11
 */
@Api(tags = "会员账号绑定")
@RestController
@RequestMapping("/api/core/userBind")
@Slf4j
public class UserBindController {

    @Autowired
    UserBindService userBindService;

    @ApiOperation("绑定会员账号")
    @PostMapping("/auth/bind")
    public R bind(@ApiParam("用户绑定Vo") @RequestBody UserBindVO userBindVo, HttpServletRequest request)
    {
        // 1、从header中取出token，验证token是否有效【是否登录】，并从token中获取到用户Id
        Long userId = JwtUtils.getUserId(request.getHeader("token"));

        // 2、根据 UserId 绑定
        String formStr = userBindService.commitBindUser(userBindVo, userId);
        return R.ok().data("formStr", formStr);
    }

    @ApiOperation("回调接口")
    @PostMapping("/notify")
    public String notify(HttpServletRequest request)
    {
        Map<String, Object> paramMap = RequestHelper.switchMap(request.getParameterMap());
        log.info("回调参数{}", paramMap);
        // 验签
        if(!RequestHelper.isSignEquals(paramMap))
        {
            log.error("用户账号绑定异步回调签名验证错误:{}", JSON.toJSONString(paramMap));
        }
        log.info("验签成功，开始绑定");
        userBindService.notify(paramMap);
        return "success";
    }
}

